package com.gitee.feizns.web.dao.handler.meta;

import com.gitee.feizns.StringUtils;
import com.gitee.feizns.bean.Property;
import com.gitee.feizns.reflect.ConstructorUtils;
import com.gitee.feizns.web.dao.ar.AbstractModel;
import com.gitee.feizns.web.dao.handler.meta.annotation.RedundancyBy;

/**
 * @author feizns
 * @since 2019/7/25
 */
public class RedundancyAutoFillHandler extends AbstractGeneralFillInputHandler {

    @Override
    protected void handle(Property<Object, Object> prop, Object original) {
        RedundancyBy by = prop.getAnnotation(RedundancyBy.class);
        if ( by != null )
            fillProp(prop, original, by);
    }

    private void fillProp(Property prop, Object original, RedundancyBy by) {
        Class<? extends AbstractModel> value = by.value();
        AbstractModel model = ConstructorUtils.newInstance(value);

        String selectField = by.field().isEmpty() ? prop.name() : by.field();

        String byFieldName;
        Object byFieldVal;

        //条件为空：查询表名 + 主键字段名

        if ( by.by().isEmpty() ) {
            byFieldName = by.byField().isEmpty() ? model.pkField().getName() : by.byField();
            String propName = StringUtils.firstLower(value.getSimpleName()) + StringUtils.firstUpper(byFieldName);
            byFieldVal = Property.of(original, propName).val();
        } else {
            byFieldName = by.byField().isEmpty() ? by.by() : by.byField();
            byFieldVal = Property.of(original, StringUtils.underlineToHump(by.by())).val();
        }

        if ( byFieldVal != null ) {
            selectField = StringUtils.toUnderline(selectField);
            byFieldName = StringUtils.toUnderline(byFieldName);
            Object ret = model.selectObj(selectField, String.format("%s = {0}", byFieldName), byFieldVal);
            prop.set(ret);
        }
    }


}
